import React, { useRef, useState, useMemo, useEffect } from 'react'
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table'
import { DnFC } from '@designable/react'
import { Button, Space, Typography, message, Form } from 'antd'
import { useT } from '@designable/event-system'
import { useForm, observer, useFieldSchema } from '@formily/react'
import { PlusOutlined } from '@ant-design/icons'
import { getUrlAllParams, getUrlParam, request } from '@designable/event-system'
import SelectGoodsModal from './SelectGoodsModal'
import { FormInstance, ProFormSelect } from '@ant-design/pro-components'

interface EditableTableProps {
  value?: any
  onChange?: (value: any) => void
  scroll?: { x?: number; y?: number }
}

function equityListNetworkGroup(params: { projectId: string }) {
  return request({
    uri: '/api/tenant/global/equity/equity/listNetworkGroup',
    params,
    method: 'POST',
  })
}

let CacheNetworkGroup = []

export const CouponGoodsTableSelector: DnFC<EditableTableProps> = observer(
  (props) => {
    const $t = useT()
    const { value, onChange } = props
    const form = useForm()
    const formValues = form.getFormState().values
    const customerCode = formValues.customerCode
    const agreementCode = formValues.agreementCode
    const actionRef = useRef<ActionType>()
    const [editableKeys, setEditableKeys] = useState<any[]>([])
    const [selectGoodsVisible, setSelectGoodsVisible] = useState(false)
    const { couponCode, canModify } = getUrlAllParams() as any

    const schema = useFieldSchema() || ({} as any)
    const name = schema.name || 'couponProductInfoList'
    const [antdForm] = Form.useForm()

    useEffect(() => {
      antdForm.setFieldValue('networkGroup', undefined)
    }, [editableKeys])
    // 是否只读
    const readonly = !(canModify === 'true' || !couponCode)

    const columns: ProColumns[] = useMemo(() => {
      return [
        {
          width: 120,
          title: $t('商品编号'),
          dataIndex: 'proCode',
          search: false,
          ellipsis: true,
          editable: false,
        },
        {
          title: $t('商品名称'),
          dataIndex: 'proName',
          ellipsis: true,
          editable: false,
        },
        {
          width: 150,
          title: $t('品类类型'),
          dataIndex: 'categoryTypeName',
          ellipsis: true,
          render: (text, record) => {
            return record.subTypeName
              ? `${record.categoryTypeName} / ${record.subTypeName}`
              : record.categoryTypeName
          },
          editable: false,
        },
        {
          width: 100,
          title: $t('可售库存'),
          dataIndex: 'stockNum',
          search: false,
          render: (_: any, record) => {
            const { stockLimit, availableStockNum } = record
            return stockLimit ? availableStockNum : $t('不限制')
          },
          editable: false,
        },
        {
          width: 100,
          title: $t('状态'),
          dataIndex: 'proStatusName',
          ellipsis: true,
          search: false,
          editable: false,
        },
        {
          width: 100,
          title: $t('网点分组'),
          dataIndex: 'networkGroupName',
          ellipsis: true,
          search: false,
          editable: false,
          hideInTable: editableKeys.length > 0,
        },
        {
          width: 150,
          title: $t('网点分组'),
          dataIndex: 'networkGroup',
          ellipsis: true,
          search: false,
          hideInTable: editableKeys.length === 0,
          valueType: 'select',
          render: (text, record) => {
            return record.networkGroupName
          },
          renderFormItem: (column, { record }, form) => {
            return (
              <ProFormSelect
                key={record.proCode}
                noStyle
                name="networkGroup"
                request={async () => {
                  const data: any = await equityListNetworkGroup({
                    projectId: record.projectId,
                  })
                  CacheNetworkGroup = data
                  return data
                }}
              />
            )
          },
        },
        {
          width: 100,
          title: $t('操作'),
          valueType: 'option',
          ellipsis: true,
          search: false,
          hideInTable: readonly,
          render: (_, record) => {
            const { proCode } = record
            return (
              <Space>
                <Typography.Link
                  onClick={() => {
                    if (editableKeys.length > 0) {
                      message.error($t('请先保存当前行'))
                      return
                    }
                    setEditableKeys([proCode])
                  }}
                >
                  {$t('编辑')}
                </Typography.Link>
                <Typography.Link
                  onClick={() => {
                    const list = form.getFormState().values[name] || []
                    const newList = list.filter(
                      (item: any) => item.proCode !== proCode
                    )
                    form?.setValues?.({
                      [name]: newList,
                      proCodeList: newList.map((item: any) => item.proCode),
                      useTypes: [
                        ...new Set(
                          newList.map((item: any) => item.productType)
                        ),
                      ],
                    })
                  }}
                >
                  {$t('删除')}
                </Typography.Link>
              </Space>
            )
          },
        },
      ]
    }, [editableKeys, readonly])
    const scrollConfig = useMemo(() => {
      return {
        x: props.scroll?.x,
        y: props.scroll?.y,
      }
    }, [props.scroll])

    return (
      <>
        <EditableProTable
          style={{ width: 860 }}
          actionRef={actionRef}
          rowKey={'proCode'}
          columns={columns}
          recordCreatorProps={false}
          toolBarRender={null}
          search={false}
          rowSelection={false}
          pagination={false}
          scroll={scrollConfig}
          value={value}
          onChange={(value) => {
            onChange?.(value)
          }}
          editable={{
            form: antdForm,
            type: 'single',
            editableKeys,
            onChange: setEditableKeys,
            actionRender: (row: any, config, defaultDom) => {
              return [defaultDom.save, defaultDom.cancel]
            },
            onSave: (rowKey: any, row: any) => {
              const networkGroup = CacheNetworkGroup.find(
                (item: any) => item.value === row.networkGroup
              )
              if (!row.networkGroup) {
                row.networkGroupName = undefined
                return Promise.resolve(row)
              }
              networkGroup && (row.networkGroupName = networkGroup?.label)
              return Promise.resolve(row)
            },
            onCancel: () => {
              setEditableKeys([])
              return Promise.reject()
            },
          }}
        />
        {!readonly && (
          <Button
            style={{ width: 860, marginTop: 10 }}
            icon={<PlusOutlined />}
            block
            onClick={() => {
              if (!customerCode) {
                message.error($t('请先选择客户'))
                return
              }
              setSelectGoodsVisible(true)
            }}
          >
            {$t('添加商品')}
          </Button>
        )}
        <SelectGoodsModal
          agreementCode={agreementCode}
          customerCode={customerCode}
          productList={value}
          visible={selectGoodsVisible}
          onOk={(data: any) => {
            form?.setValues?.({
              [name]: data,
              proCodeList: data.map((item: any) => item.proCode),
              useTypes: [...new Set(data.map((item: any) => item.productType))],
              couponType: 'discount',
            })
            setSelectGoodsVisible(false)
            return Promise.resolve()
          }}
          onCancel={() => setSelectGoodsVisible(false)}
        />
      </>
    )
  }
)
